import json
import time
import traceback

from loguru import logger
from sqlalchemy.orm import sessionmaker

from conf import Config as myconf
from dl.download_ref_pdf import DRPdf
from models.table_defs import TaskQueue
from utils.DbHelper2023 import DbHelper

from utils.comm_preemptive_task import CommPreemptiveTask

Tbl_queue = "task_queue"


class DownloadDOIMgr:
  def __init__(self):
    self.is_running = True
    self.dbHelper = DbHelper(configFile0=myconf.doidl_db_config, db_type= DbHelper.DB_TYPE_SQLITE)
    self.commPreemptiveTask = CommPreemptiveTask(Tbl_queue, self.dbHelper, self.runner1)
    self.sessionmaker = sessionmaker(bind=self.dbHelper.get_enginee())

  def start_task(self):
    while self.is_running:
      self.commPreemptiveTask.call()
      time.sleep(5)  # 控制任务执行的时间间隔

  def stop_task(self):
    self.is_running = False  # 设置标志位，退出循环
    logger.info("set DownloadDOIMgr.is_running = False to exit task loop")

  def runner1(self, biz_id, task_id):
    logger.info(f"in runner1, biz_id={biz_id}, task_id={task_id}")
    return self.start_download(biz_id)

  def start_download(self, id):
    sql = f"select cont from task_queue where id={id}"
    rs = self.dbHelper.run_sql_4result(sql, row_to_dict=True,rs_to_list=True, log=logger)
    if rs:
      cont = rs[0]['cont']
      jcont = json.loads(cont)
      if 'doi' in jcont:
        try:
          doi = jcont['doi']
          logger.info(f"to download doi={doi}")
          local_file = DRPdf.download_ref_pdf2_by_doi(doi)
          if local_file:
            logger.info(f"download doi={doi} success, local_file={local_file}")
            jcont['local_file'] = local_file
            upd_sql_tmpl = f"update task_queue set cont=:cont where id={id}"
            result = self.dbHelper.runSqlWithParas(upd_sql_tmpl, {"cont": json.dumps(jcont)})
            logger.info(f"update task_queue OK!")
            return True
          else:
            logger.error(f"download doi={doi} failed")
            return False
        except Exception as e:
          logger.error(traceback.format_exc())
          return False

  def apply_download_doi(self, doi):
    logger.info(f"apply_download_doi, doi={doi}")
    with self.sessionmaker() as session:
      new_record = TaskQueue(cont=json.dumps({"doi": doi}))
      session.add(new_record)
      session.commit()
      new_id = new_record.id
      return new_id

  def get_local_file_by_receipt_id(self, receipt_id):
    with self.sessionmaker() as session:
      task_queue = session.query(TaskQueue).filter_by(id=receipt_id).first()
      jcont = json.loads( task_queue.cont)
      if task_queue.sts == 4: # 下载已失败
        return task_queue.sts, '', jcont['doi']
      elif task_queue.sts <= 1:  # 还未下载
        return task_queue.sts, '', jcont['doi']
      elif 'local_file' in jcont:
        return task_queue.sts, jcont['local_file'] , jcont['doi']
      else:
        return None,None,None

# test code
def test1():
  mgr = DownloadDOIMgr()

  pass



if __name__ == '__main__':
  test1()
  # test_call_ai()
